package com.zjt.pictureselector.Util;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.zjt.pictureselector.model.FolderBean;
import com.zjt.pictureselector.model.MediaBean;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <P>Company: </p>
 *
 * @author zhengjianting
 * @time 2017/11/10 0010 下午 5:43
 */

public class PictureUtil {

    private static List<MediaBean> mPictureData;
    private static List<MediaBean> mVideoData;
    private static boolean isGetPic = false;
    private static boolean isGetVideo = false;
//    private static List<MediaBean> mAllMediaData = new ArrayList<>();

    public static void getAllMedia(final Context context, final PictureDataCallback callback){
        getAllPicture(context, callback);
        getAllVideo(context, callback);
    }

    /**
     * 读取手机中所有图片信息
     */
    private static void getAllPicture(final Context context, final PictureDataCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<MediaBean> allPhotosTemp = new ArrayList<>();
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                String[] projImage = {MediaStore.Images.Media._ID
                        , MediaStore.Images.Media.DATA
                        , MediaStore.Images.Media.SIZE
                        , MediaStore.Images.Media.DISPLAY_NAME
                        , MediaStore.Images.Media.DATE_ADDED
                        , MediaStore.Images.Media.DATE_MODIFIED};

                Cursor mCursor = context.getContentResolver().query(
                        mImageUri,
                        projImage,
                        MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED + " desc");

                if (mCursor != null) {
                    while (mCursor.moveToNext()) {
                        String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        long size = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Images.Media.SIZE)) / 1024;
                        String displayName = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
                        long addTime = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED));

                        if (!".downloading".equals(path)){
                            allPhotosTemp.add(new MediaBean(MediaBean.Type.Image, path, size, displayName, addTime));
                        }
                    }
                    mCursor.close();
                }
                mPictureData = allPhotosTemp;
                isGetPic = true;
                mergerPicData(callback);

            }
        }).start();
    }

    /**
     * 获取手机中所有视频的信息
     */
    private static void getAllVideo(final Context context, final PictureDataCallback callback){
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<MediaBean> allVideosTemp = new ArrayList<>();
                Uri mImageUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                String[] proj = {MediaStore.Video.Thumbnails._ID
                        , MediaStore.Video.Thumbnails.DATA
                        , MediaStore.Video.Media.DURATION
                        , MediaStore.Video.Media.SIZE
                        , MediaStore.Video.Media.DISPLAY_NAME
                        , MediaStore.Video.Media.DATE_ADDED
                        , MediaStore.Video.Media.DATE_MODIFIED};

                Cursor mCursor = context.getContentResolver().query(
                        mImageUri,
                        proj,
                        MediaStore.Video.Media.MIME_TYPE + "=?",
                        new String[]{"video/mp4"},
                        MediaStore.Video.Media.DATE_MODIFIED + " desc");
                if (mCursor != null) {
                    while (mCursor.moveToNext()) {
                        int videoId = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Video.Media._ID));
                        String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Video.Media.DATA));
                        int duration = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Video.Media.DURATION));
                        long size = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Video.Media.SIZE)) / 1024; //单位kb
                        if (size < 0) {
                            //某些设备获取size<0，直接计算
                            Log.e("dml", "this video size < 0 " + path);
                            size = new File(path).length() / 1024;
                        }
                        String displayName = mCursor.getString(mCursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
                        long addTime = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED));
                        long modifyTime = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED));//暂未用到

                        //提前生成缩略图，再获取：http://stackoverflow.com/questions/27903264/how-to-get-the-video-thumbnail-path-and-not-the-bitmap
                        MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(), videoId, MediaStore.Video.Thumbnails.MICRO_KIND, null);

                        String[] projection = {MediaStore.Video.Thumbnails._ID, MediaStore.Video.Thumbnails.DATA};
                        Cursor cursor = context.getContentResolver().query(
                                MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI
                                , projection
                                , MediaStore.Video.Thumbnails.VIDEO_ID + "=?"
                                , new String[]{videoId + ""}
                                , null);
                        String thumbPath = "";
                        while (cursor.moveToNext()) {
                            thumbPath = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
                        }
                        cursor.close();

                        allVideosTemp.add(new MediaBean(MediaBean.Type.Video, path, thumbPath, duration, size, displayName, addTime));
                    }
                    mCursor.close();
                }
                mVideoData = allVideosTemp;
                isGetVideo = true;
                mergerPicData(callback);

            }
        }).start();
    }

    private static synchronized void mergerPicData(final PictureDataCallback callback){
        if (isGetPic && isGetVideo) {
            List<MediaBean> mAllMediaData = new ArrayList<>();
            mAllMediaData.addAll(mPictureData);
            mAllMediaData.addAll(mVideoData);
            Collections.sort(mAllMediaData);
            callback.onSuccess(splitFolder(mAllMediaData));
        }
    }

    /**
     * 把图片按文件夹拆分，第一个文件夹保存所有的图片
     *
     * @param mediaBeanList
     * @return
     */
    private static ArrayList<FolderBean> splitFolder(List<MediaBean> mediaBeanList) {
        ArrayList<FolderBean> folderList = new ArrayList<>();
        folderList.add(new FolderBean("全部图片", mediaBeanList));

        if (mediaBeanList != null && !mediaBeanList.isEmpty()) {
            for (int i = 0; i < mediaBeanList.size(); i++) {
                String path = mediaBeanList.get(i).getPath();
                String name = getFolderName(path);
                if (!TextUtils.isEmpty(name)) {
                    FolderBean folder = getFolder(name, folderList);
                    folder.addMediaBean(mediaBeanList.get(i));
                }
            }
        }
        return folderList;
    }

    /**
     * 跟着图片路径，获取图片文件夹名称
     *
     * @param path
     * @return
     */
    private static String getFolderName(String path) {
        if (!TextUtils.isEmpty(path)) {
            String[] strings = path.split(File.separator);
            if (strings.length >= 2) {
                return strings[strings.length - 2];
            }
        }
        return "";
    }

    private static FolderBean getFolder(String name, List<FolderBean> folderList) {
        if (!folderList.isEmpty()) {
            for (int i = 0; i < folderList.size(); i++) {
                FolderBean folder = folderList.get(i);
                if (name.equals(folder.getFolderName())) {
                    return folder;
                }
            }
        }
        FolderBean newFolder = new FolderBean(name);
        folderList.add(newFolder);
        return newFolder;
    }

    public interface PictureDataCallback{
        void onSuccess(List<FolderBean> folderBeanList);
    }
}
